package yxy.game.pm2.command.hero;

import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.hero.HeroModule;

@MessageType(proto = Command.HerosUpper, classtype = HeroMessage.HerosUpperRequest.class)
public class CMD_HerosUpper extends Command<HeroMessage.HerosUpperRequest> {

	@Override
	public void execute(MessageSource messageSource, HeroMessage.HerosUpperRequest request) {
		String playerCode = messageSource.getTag();

		HeroMessage.HerosUpperResponse.Builder response = HeroMessage.HerosUpperResponse.newBuilder();

		HeroModule heroModule = HeroModule.get(playerCode);

		try {
			if (heroModule.tryLock()) {

				HeroHandle heroHandle = new HeroHandle();
				if (heroHandle.isUpper(heroModule)) {
					send(messageSource, response, Result.HeroPackUpper);// 购买次数已达上限
					return;
				}

				int times = heroModule.getHeroPackUpperBuyTimes();
				int costNum = fomula.武将背包每次增长花费.intValue(times);
				Currency cost = Currency.create(CurrencyType.CT_元宝, 0, costNum);
				try {
					new CurrencyHandle().cost(playerCode, CCReason.武将背包, cost);
				} catch (CurrencyNotEnoughException e) {
					send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
					return;
				}
				int upper = heroHandle.buyUpper(heroModule);
				costNum = fomula.武将背包每次增长花费.intValue(times + 1);

				response.setUpper(upper);
				response.setCost(costNum);

				send(messageSource, response, Result.Success);

			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			heroModule.unlock();
		}
	}

	private void send(MessageSource messageSource, HeroMessage.HerosUpperResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}

}
